package com.exercises;

import java.util.ArrayList;
import java.util.List;

class Exercise38 {
    public static void main(String[] args) {
        System.out.println(new Exercise38().countAndSay(5));

    }


    public String countAndSay(int n) {
        if (n == 1) {
            return "1";
        }

        List<String> numberList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();

        String subStr = countAndSay(n - 1);
        Character head = null;
        int size = 0;
        for (int i = 0; i < subStr.length(); i++) {
            if (head == null || !head.equals(subStr.charAt(i))) {
                char number = subStr.charAt(i);
                head = number;
                numberList.add(String.valueOf(number));
                countList.add(1);
                size++;
            } else {
                int count = countList.get(size - 1);
                countList.set(size - 1, count + 1);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < numberList.size(); i++) {
            stringBuilder.append(countList.get(i)).append(numberList.get(i));
        }
        return stringBuilder.toString();

    }


}
